import React, { useEffect, useRef, useState, useLayoutEffect } from 'react';
import * as echarts from 'echarts';
import style from './styles.css';
import { BorderBox12, BorderBox13 } from '@jiaminghi/data-view-react';
import { ModuleTitle } from '../../style/globalStyledSet';

import { CenterPage, CenterBottom } from './style';
import * as dashboardApi from '../../services/api'; // 根据你的实际路径调整

//1-图表配置工具函数
//1-1使用图
const USAGE_Chart_CONFIG = (data) => ({
  tooltip: {
    trigger: 'item',
  },
  legend: {
    orient: 'vertical', // 垂直排列
    right: '15%', // 距离右侧 10px
    top: 'center', // 垂直居中
    itemWidth: 10,
    itemHeight: 10,
    textStyle: {
      color: 'rgba(255,255,255,.5)',
      // fontSize: "12"
    },
  },
  color: [
    '#006cff',
    '#60cda0',
    '#ed8884',
    '#ff9f7f',
    '#0096ff',
    '#9fe6b8',
    '#32c5e9',
    '#1d9dff',
  ],
  series: [
    {
      name: '工具调用次数',
      type: 'pie',
      // radius: [20, 100],
      radius: ['10%', '70%'],
      center: ['35%', '50%'],
      roseType: 'radius',
      itemStyle: {
        borderRadius: 8,
      },
      // 修饰饼形图文字相关的样式 label对象
      label: {
        fontSize: 10,
      },
      // 修饰引导线样式
      labelLine: {
        // 连接到图形的线长度
        length: 10,
        // 连接到文字的线长度
        length2: 10,
      },
      data: data.series,
    },
  ],
});

//1-2对比图
const COMPARE_CHART_CONFIG = (data) => ({
  title: {
    text: '数字化应用-事业部对比',
    textStyle: {
      color: '#bad9ed', // 修改为任意颜色值（如橙色）
    },
    left: 'center',
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow',
    },
    textStyle: {
      fontSize: 14,
    },
    formatter: function (params) {
      let result = [
        `<div style="font-weight: bold;">${params[0].axisValue}</div>`,
      ];
      let resultSpilt = [
        `<div style="font-weight: bold; margin: 4px 0px;">---------------------------</div>`,
      ];
      params.forEach((param) => {
        if (param.value !== 0) {
          if (param.seriesName.includes('人均使用频次')) {
            result.push(`
                <div>
                  <span style="color: ${param.color}">●</span>
                  ${param.seriesName}: ${param.value}
                </div>
              `);
          }
          if (param.seriesName.includes('职群推广占比')) {
            resultSpilt.push(`
                <div>
                  <span style="color: ${param.color}">●</span>
                  ${param.seriesName}: ${(param.value * 100).toFixed(2)}$
                </div>
              `);
          }
        }
      });
      if (resultSpilt.length > 1) {
        return result.join('') + resultSpilt.join('');
      } else {
        return result.join('');
      }
    },
  },
  legend: {
    type: 'scroll',
    orient: 'vertical',
    right: '0px', // 距离右侧 10px
    top: 'center', // 垂直居中
    height: '80%', // 高度限制（防止超出容器）
    itemGap: 10,
    // data: [
    //   ...data.uniqToolTypes.map((dept) => dept + '-人均使用频次'),
    //   ...data.uniqToolTypes.map((dept) => dept + '-职群推广占比'),
    // ],
    textStyle: {
      // 图例文本样式配置
      color: 'rgba(255,255,255,.5)',
    },
    pageTextStyle: {
      // 分页按钮文字样式
      color: '#CCCCCC',
    },
  },
  grid: {
    top: '13%',
    left: '3%',
    right: '27%',
    bottom: '3%',
    containLabel: true,
  },
  xAxis: {
    type: 'category',
    data: data.departments,
    boundaryGap: false,
    axisLabel: {
      color: '#bad9ed',
      interval: 0,
    },
    axisLine: {
      lineStyle: {
        type: 'solid',
      },
    },
  },
  yAxis: [
    {
      type: 'value',
      min: 1,
      max: 90000,
      name: '人均频次',
      axisLabel: {
        color: '#bad9ed',
      },
      nameTextStyle: {
        // 名称文本样式配置
        color: '#bad9ed', // 字体颜色（示例改为橙色）
      },
      // 修改y轴分割线的颜色
      splitLine: {
        lineStyle: {
          color: '#012f4a',
        },
      },
    },
    {
      type: 'value',
      min: 0,
      max: 2,
      name: '推广占比',
      axisLabel: {
        color: '#bad9ed',
        formatter: function (value) {
          // 更安全的百分比格式化
          return Math.round(value * 100 * 100) / 100 + '%'; // 保留两位小数
        },
      },
      nameTextStyle: {
        // 名称文本样式配置
        color: '#bad9ed', // 字体颜色（示例改为橙色）
      },
      // 修改y轴分割线的颜色
      splitLine: {
        lineStyle: {
          color: '#012f4a',
        },
      },
    },
  ],
  series: [
    ...data.uniqToolTypes.map((toolType) => ({
      name: `${toolType}-人均使用频次`,
      type: 'bar',
      stack: 'usage',
      yAxisIndex: 0,
      data: data.departments.map((dept) => {
        const match = data.perUsageFrequency.find(
          (d) => d.departmentName === dept && d.toolType === toolType,
        );
        return match ? match.perCapitaUsageFrequency : null;
      }),
    })),
    ...data.uniqToolTypes.map((toolType) => ({
      name: `${toolType}-职群推广占比`,
      type: 'bar',
      stack: 'promotion',
      yAxisIndex: 1,
      data: data.departments.map((dept) => {
        const match = data.promotionRatio.find(
          (d) => d.departmentName === dept && d.toolType === toolType,
        );
        return match ? match.promotionRate : null;
      }),
    })),
  ],
});

//1-3趋势图
const colors = [
  '#0184d5',
  '#FF9F43',
  '#27AE60',
  '#E74C3C',
  '#9B59B6',
  '#3498DB',
  '#F1C40F',
  '#1ABC9C',
  '#D35400',
  '#34495E',
];
const TREND_CHART_CONFIG = (data) => ({
  title: {
    text: '数字化应用 - 趋势',
    textStyle: {
      color: '#bad9ed', // 修改为任意颜色值（如橙色）
    },
    left: 'center',
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow',
    },
    textStyle: {
      fontSize: 14,
    },
    formatter: function (params) {
      let result = [
        `<div style="font-weight: bold;">${params[0].axisValue}</div>`,
      ];
      params.forEach((param) => {
        if (param.value !== 0) {
          result.push(`
            <div>
              <span style="color: ${param.color}">●</span>
              ${param.seriesName}: ${(param.value * 100).toFixed(2)}%
            </div>
          `);
        }
      });
      return result.join('');
    },
  },
  legend: {
    type: 'scroll',
    orient: 'vertical',
    right: '0px', // 距离右侧 10px
    top: 'center', // 垂直居中
    height: '80%', // 高度限制（防止超出容器）
    itemGap: 10,
    // data: [
    //   ...data.uniqToolTypes.map((dept) => dept + '-人均使用频次'),
    //   ...data.uniqToolTypes.map((dept) => dept + '-职群推广占比'),
    // ],
    textStyle: {
      // 图例文本样式配置
      color: 'rgba(255,255,255,.5)',
    },
    pageTextStyle: {
      // 分页按钮文字样式
      color: '#CCCCCC',
    },
  },
  grid: {
    top: '13%',
    left: '3%',
    right: '25%',
    bottom: '3%',
    containLabel: true,
  },
  xAxis: {
    type: 'category',
    data: data.months,
    boundaryGap: false,
    axisLabel: {
      color: '#bad9ed',
      interval: 0,
    },
  },
  yAxis: [
    {
      type: 'value',
      min: 1,
      max: 90000,
      name: '人均频次',
      axisLabel: {
        color: '#bad9ed',
      },
      nameTextStyle: {
        // 名称文本样式配置
        color: '#bad9ed', // 字体颜色（示例改为橙色）
      },
      // 修改y轴分割线的颜色
      splitLine: {
        lineStyle: {
          color: '#012f4a',
        },
      },
    },
    {
      type: 'value',
      min: 0,
      max: 2,
      name: '推广占比',
      axisLabel: {
        color: '#bad9ed',
        formatter: function (value) {
          // 更安全的百分比格式化
          return Math.round(value * 100 * 100) / 100 + '%'; // 保留两位小数
        },
      },
      nameTextStyle: {
        // 名称文本样式配置
        color: '#bad9ed', // 字体颜色（示例改为橙色）
      },
      // 修改y轴分割线的颜色
      splitLine: {
        lineStyle: {
          color: '#012f4a',
        },
      },
    },
  ],

  series: [
    ...data.departments.map((dept, index) => ({
      name: `${dept}-人均使用频次`,
      type: 'line',
      yAxisIndex: 0,
      itemStyle: {
        color: colors[index % colors.length],
      }, // 循环取色
      lineStyle: {
        color: colors[index % colors.length], // 设置线条颜色
        width: 2,
      },
      smooth: true,
      symbol: 'circle',
      symbolSize: 5,
      showSymbol: false,
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: colors[index % colors.length] + '80' },
          { offset: 1, color: colors[index % colors.length] + '20' },
        ]),
      },
      data: data.months.map((month) => {
        const match = data.perUsageFrequency.find(
          (d) => d.departmentName === dept && d.month === month,
        );
        return match ? match.perCapitaUsageFrequency : null;
      }),
    })),
    ...data.departments.map((dept, index) => ({
      name: `${dept}-职群推广占比`,
      type: 'line',
      smooth: true,
      yAxisIndex: 1,
      itemStyle: {
        color: colors[(index + 2) % colors.length],
      },
      lineStyle: {
        type: 'dashed',
        color: colors[(index + 2) % colors.length], // 设置虚线颜色
        width: 2,
      },
      symbol: 'circle',
      symbolSize: 5,
      showSymbol: false,
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: colors[(index + 2) % colors.length] + '80' },
          { offset: 1, color: colors[(index + 2) % colors.length] + '20' },
        ]),
      },
      data: data.months.map((month) => {
        const match = data.promotionRatio.find(
          (d) => d.departmentName === dept && d.month === month,
        );
        return match ? match.promotionRate : null;
      }),
    })),
  ],
});

//2-数据处理函数
//2-1 对比/趋势图数据处理
const processData = (rawData) => {
  const uniqueDepts = [...new Set(rawData.map((item) => item.departmentName))];
  const uniqueMonths = [...new Set(rawData.map((item) => item.month))];
  const uniqToolTypes = [...new Set(rawData.map((item) => item.toolType))];

  return {
    departments: uniqueDepts,
    months: uniqueMonths,
    uniqToolTypes: uniqToolTypes,
    perUsageFrequency: rawData.filter((r) => r.type === '人均使用频次'),
    promotionRatio: rawData.filter((r) => r.type === '职群推广占比'),
  };
};
//2-2使用图数据处理
const processUsageData = (rawData) => {
  const uniqToolTypes = [...new Set(rawData.map((item) => item.toolType))];
  // 准备 series 数据
  var series = [];
  uniqToolTypes.forEach((toolType) => {
    const foundData = rawData.find((d) => d.toolType === toolType); // 直接使用 find()
    if (foundData) {
      series.push({
        name: toolType,
        value: foundData.toolTotalCallNumber, //工具总调用次数
      });
    } else {
      console.warn(`No data found for tooltype: ${toolType}`);
    }
  });
  console.log('series', series);
  return {
    toolTypes: uniqToolTypes,
    series: series,
  };
};

//3-主体
const DigitalApplication = () => {
  const trendChartRef = useRef(null);
  const compareChartRef = useRef(null);
  const usageChartRef = useRef(null);
  const [compareData, setCompareData] = useState(null);
  const [trendData, setTrendData] = useState(null);
  const [usageData, setUsageData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  //3-1创建数据获取函数
  const fetchData = async () => {
    try {
      setLoading(true);
      // 并行请求数据
      const [responseByBu, responseByTrend, responseByUsage] =
        await Promise.all([
          dashboardApi.getDigitalApplicationsByBuAsync(),
          dashboardApi.getDigitalApplicationsByTrendAsync(),
          dashboardApi.getDigitalApplicationsByUsuageAsync(2),
        ]);
      setCompareData(processData(responseByBu.data.content));
      setTrendData(processData(responseByTrend.data.content));
      setUsageData(processUsageData(responseByUsage.data.content));
    } catch (err) {
      setError(err.message || '获取数据失败');
      console.error('API调用错误:', err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
    return () => {
      [trendChartRef, compareChartRef, usageChartRef].forEach((ref) => {
        if (ref.current) echarts.dispose(ref.current);
      });
    };
  }, []);

  //3-2-1.使用图
  useLayoutEffect(() => {
    if (!usageData || !usageChartRef.current) {
      console.log('使用图表还不能初始化，等待数据和DOM');
      return;
    }
    console.log('使用图表开始初始化');
    const usageChart = echarts.init(usageChartRef.current);
    usageChart.setOption(USAGE_Chart_CONFIG(usageData));
    window.addEventListener('resize', () => usageChart.resize());

    return () => {
      usageChart.dispose(); // 清理趋势图实例
    };
  }, [usageData]); // 依赖 data 属性变化
  //3-2-2. 对比图
  useLayoutEffect(() => {
    if (!compareData || !compareChartRef.current) {
      console.log('1对比图表还不能初始化，等待数据和DOM');
      return;
    }
    console.log('1对比图表开始初始化');

    // 对比图
    const compareChart = echarts.init(compareChartRef.current);
    compareChart.setOption(COMPARE_CHART_CONFIG(compareData));
    window.addEventListener('resize', () => compareChart.resize());
    return () => {
      compareChart.dispose(); // 清理对比图实例
    };
  }, [compareData]); // 依赖 data 属性变化
  //3-2-3.趋势图
  useLayoutEffect(() => {
    if (!trendData || !trendChartRef.current) {
      console.log('1趋势图表还不能初始化，等待数据和DOM');
      return;
    }
    console.log('1趋势图表开始初始化');
    // 1. 趋势图
    const trendChart = echarts.init(trendChartRef.current);
    trendChart.setOption(TREND_CHART_CONFIG(trendData));
    window.addEventListener('resize', () => trendChart.resize());

    return () => {
      trendChart.dispose(); // 清理趋势图实例
    };
  }, [trendData]); // 依赖 data 属性变化

  return (
    <CenterPage>
      <br />
      <ModuleTitle style={{ textAlign: 'left', width: '100%' }}>
        <i className="iconfont">&#xe7f7;</i>
        <span>数字化应用</span>
      </ModuleTitle>

      {/* <BorderBox12 className={style["chart"]}> */}
      <BorderBox12 style={{ height: '3.625rem' }}>
        <div
          ref={usageChartRef}
          style={{ height: '3.125rem', margin: '0.0625rem' }}
        ></div>
      </BorderBox12>

      <BorderBox12 style={{ height: '4rem' }}>
        <br />
        <div
          ref={compareChartRef}
          style={{
            width: '100%',
            height: '3.2rem',
            mariginTop: '1rem',
          }}
        ></div>
      </BorderBox12>

      <BorderBox12 style={{ height: '4rem' }}>
        <br />
        <div
          ref={trendChartRef}
          style={{
            width: '100%',
            height: '3.2rem',
          }}
        ></div>
      </BorderBox12>
    </CenterPage>
  );
};

export default DigitalApplication;
